<template>
  <div id="app">
    <!-- <router-view /> -->
    <div>
      {{ address }}
      {{ usdtBalance }}
    </div>
    <button @click="fetchUsdt">fetchUsdt</button>
    <button @click="sendUsdt">sendUsdt</button>
  </div>
</template>

<script setup lang="ts">
import VConsole from 'vconsole';
let vConsole = new VConsole();



import { ref, onMounted } from 'vue'

const address = ref('')
const usdtBalance = ref('0')
const USDT_CONTRACT_ADDRESS = 'TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t'

onMounted(async () => {
  const okxTron = window.okxwallet?.tronLink
  if (!okxTron) {
    console.warn('OKX Tron 钱包未注入')
    return
  }

  // 请求授权
  await okxTron.request({ method: 'tron_requestAccounts' })

  // 获取地址
  const walletAddr = okxTron.tronWeb?.defaultAddress?.base58
  if (walletAddr) {
    address.value = walletAddr
    await fetchUsdt()
  }

  // 监听地址变更
  window.addEventListener('message', e => {
    if (e.data?.message?.action === 'accountsChanged') {
      const newAddr = e.data.message.data.address
      if (newAddr) {
        address.value = newAddr
        fetchUsdt()
      }
    }
  })
})
import BigNumber from 'bignumber.js'

// 获取 USDT 余额
async function fetchUsdt() {
  if (!address.value) {
    console.warn('地址为空，跳过 USDT 获取')
    return
  }

  const tronWeb = window.okxwallet.tronLink.tronWeb
  console.log(tronWeb, 'tronWeb');

  const contract = await tronWeb.contract().at(USDT_CONTRACT_ADDRESS)
  console.log(contract, 'contract');

  const raw = await contract.methods.balanceOf(address.value).call()
  console.log(raw, 'raw');
  // 提取 _hex 属性中的十六进制数值
  const rawHex = raw._hex

  // 用 BigNumber 处理余额
  usdtBalance.value = new BigNumber(rawHex).dividedBy(1e6).toFixed(2)

}
// 转账 USDT
// to, amount
async function sendUsdt() {
  let to = 'TFgx9wEKyATa4BfaniE6VcTBonax1ro26w'
  let amount = '1'
  const contract = await window.okxwallet.tronLink.tronWeb.contract().at(USDT_CONTRACT_ADDRESS)
  await contract.methods.transfer(to, amount * 1e6).send({ feeLimit: 1e8, callValue: 0 })
}
</script>

<style>
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', sans-serif;
  background-color: #f5f5f5;
  color: #333;
}

#app {
  min-height: 100vh;
  overflow-x: hidden;
}
</style>